# 1.自动生成HTML标签
# 2.表单验证
import datetime
from web import models
from .base import BootStrapModelForm
from django import forms

class TaskModelForm(BootStrapModelForm):
    # 生成新字段,需要新添加字段
    # 利用之前定义的基类中的`exclude_bootstrap=[]`来控制样式的添加
    # checkbox无需添加样式


    # 自己定义新的字段
    # 下拉框 checkbox 文本框
    before_download_select = forms.ChoiceField(required=False, label='下载前')
    before_download_title = forms.CharField(required=False, label='模板名称')
    before_download_template = forms.BooleanField(required=False, widget=forms.CheckboxInput, label='是否保存为模板')

    after_download_select = forms.ChoiceField(required=False, label='下载后')
    after_download_title = forms.CharField(required=False, label='模板名称')
    after_download_template = forms.BooleanField(required=False, widget=forms.CheckboxInput, label='是否保存为模板')

    before_deploy_select = forms.ChoiceField(required=False, label='发布前')
    before_deploy_title = forms.CharField(required=False, label='模板名称')
    before_deploy_template = forms.BooleanField(required=False, widget=forms.CheckboxInput, label='是否保存为模板')

    after_deploy_select = forms.ChoiceField(required=False, label='下载后')
    after_deploy_title = forms.CharField(required=False, label='模板名称')
    after_deploy_template = forms.BooleanField(required=False, widget=forms.CheckboxInput, label='是否保存为模板')

    class Meta:
        model = models.DeployTask
        # fields = "__all__"
        exclude = ['uid', 'project', 'status']

    def __init__(self, project_object, *args, **kwargs):
        super().__init__(*args, **kwargs)  # *args, **kwargs是request.POST里的，project_id是单独传
        self.project_object = project_object
        self.init_hook()

    def init_hook(self):
        # 给所有的下拉框先添加一个 请选择选项
        # <option value="0">请选择</option>  (0,'请选择')

        before_download = [(0, '请选择')]
        # 还应该去数据库中查询是否有对应的模版名称
        extra_list = models.HookTemplate.objects.filter(hook_type=2).values_list('pk', 'title')
        # 利用extend扩展列表 (append只是添加)
        before_download.extend(extra_list)
        self.fields['before_download_select'].choices = before_download

        after_download = [(0, '请选择')]
        extra_list = models.HookTemplate.objects.filter(hook_type=4).values_list('pk', 'title')
        after_download.extend(extra_list)
        self.fields['after_download_select'].choices = after_download

        before_deploy = [(0, '请选择')]
        extra_list = models.HookTemplate.objects.filter(hook_type=6).values_list('pk', 'title')
        before_deploy.extend(extra_list)
        self.fields['before_deploy_select'].choices = before_deploy

        after_deploy = [(0, '请选择')]
        extra_list = models.HookTemplate.objects.filter(hook_type=8).values_list('pk', 'title')
        after_deploy.extend(extra_list)
        self.fields['after_deploy_select'].choices = after_deploy


    def save(self, commit=True):
        # 手动给未填写的字段赋值，没默认值，前端也未设值。 不写会添加报错：IntegrityError at /task/add/4/
        # NOT NULL constraint failed
        self.instance.uid = self.create_uid()
        self.instance.project_id = self.project_object.id

        super().save(commit=True)
        # 判断用户是否点击checkbox (保存模板到数据库)
        if self.cleaned_data.get("before_download_template"):
            # 获取模版名称
            title = self.cleaned_data.get("before_download_title")
            # 获取脚本内容
            content = self.cleaned_data.get("before_download_script")
            # 保存到表中
            models.HookTemplate.objects.create(
                title=title,
                content=content,
                hook_type=2
            )
        if self.cleaned_data.get("after_download_template"):
            # 获取模版名称
            title = self.cleaned_data.get("after_download_title")
            # 获取脚本内容
            content = self.cleaned_data.get("after_download_script")
            # 保存到表中
            models.HookTemplate.objects.create(
                title=title,
                content=content,
                hook_type=4
            )

        if self.cleaned_data.get("before_deploy_template"):
            # 获取模版名称
            title = self.cleaned_data.get("before_deploy_title")
            # 获取脚本内容
            content = self.cleaned_data.get("before_deploy_script")
            # 保存到表中
            models.HookTemplate.objects.create(
                title=title,
                content=content,
                hook_type=6
            )

        if self.cleaned_data.get("after_deploy_template"):
            # 获取模版名称
            title = self.cleaned_data.get("after_deploy_title")
            # 获取脚本内容
            content = self.cleaned_data.get("after_deploy_script")
            # 保存到表中
            models.HookTemplate.objects.create(
                title=title,
                content=content,
                hook_type=8
            )

    def create_uid(self):
        # 项目名-测试环境-版本号-时间戳
        title = self.project_object.title
        env = self.project_object.env
        # clean_data是用户提交过来的所有数据
        tag = self.cleaned_data.get('tag')
        date = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        return "{0}-{1}-{2}-{3}".format(title, env, tag, date)

    def clean(self):
        if self.cleaned_data.get('before_download_template'):
            # 获取用户输入的模版名称 判断是否有值
            title = self.cleaned_data.get("before_download_title")
            if not title:
                # 展示提示信息
                self.add_error('before_download_title','请输入模版名称')

        if self.cleaned_data.get('after_download_template'):
            # 获取用户输入的模版名称 判断是否有值
            title = self.cleaned_data.get("after_download_title")
            if not title:
                # 展示提示信息
                self.add_error('after_download_title','请输入模版名称')

        if self.cleaned_data.get('before_deploy_template'):
            # 获取用户输入的模版名称 判断是否有值
            title = self.cleaned_data.get("before_deploy_title")
            if not title:
                # 展示提示信息
                self.add_error('before_deploy_title','请输入模版名称')

        if self.cleaned_data.get('after_deploy_template'):
            # 获取用户输入的模版名称 判断是否有值
            title = self.cleaned_data.get("after_deploy_title")
            if not title:
                # 展示提示信息
                self.add_error('after_deploy_title','请输入模版名称')